package php.code.routines;

import com.google.common.base.Joiner;
import utils.titles.Title;
import php.code.Variable;
import php.code.Visibility;
import php.code.functions.Array;
import php.code.instructions.Instruction;
import php.code.instructions.VariableDeclaration;

import java.util.ArrayList;
import java.util.List;

public class Method extends Routine {
    protected final Visibility visibility;
    private final VariableDeclaration[] args;
    private final List<Variable> vars = new ArrayList<>();

    public Method(PhpClass phpClass, Visibility visibility, Title title, VariableDeclaration...args) {
        super(phpClass, title);
        this.visibility = visibility;
        this.args = args;
        for(VariableDeclaration variableDeclaration : args)
            vars.add(variableDeclaration.getVariable());
        block.content.separator("\n\n");
    }

    public Method add(Instruction instruction){
        block.content.add(instruction);
        return this;
    }

    public Method add(String... lines){
        block.content.createLiterals(lines);
        return this;
    }

    @Override
    protected String getSignature() {
        return String.format("%s function %s(%s)",
                visibility,
                getName(),
                Joiner.on(", ").join(args)
        );
    }

    public Method returns(String result) {
        add("return " + result + ";");
        return this;
    }

    public Method returns(Array<?> array) {
        array.setIndentation(block.content.getIndentation());
        add("return " + array + ";");
        return this;
    }

    public Method callParent() {
        add("parent::" + getName() + "(" + Joiner.on(", ").join(vars) +");");
        return this;
    }

    public List<Variable> getVars() {
        return new ArrayList<>(vars);
    }
}
